<template>
  <div>
    <div class="mateBox">
      <ocr-upload :stateFlag='false' v-model="card" type="idCard" front-file-type="IML010201" back-file-type="IML010202"
        :uu-id="uuid" :inst-id="instId" @getocrinfo="getOcrInfo" desc="身份证"></ocr-upload>
      <van-form @submit="onSubmit">
        <div class="box">
          <van-field v-model="metaInfo.authorizedName" name="authorizedName" label="姓名" placeholder="姓名"
            @change="authorizeNameMsg" :rules="[{ required: true, message: '请填写姓名' }]" />
          <ab-characters v-model="metaInfo.authorizedName">生僻字录入</ab-characters>
        </div>
        <div class="box">
          <van-field v-model="metaInfo.cardName" name="cardName" label="证件类型" placeholder="证件类型" readonly />
        </div>
        <div class="box">
          <van-field v-model="metaInfo.cardCode" name="cardCode" label="证件号码" placeholder="证件号码" :rules="[{
     pattern:
       /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
     message: '请输入正确格式',
     trigger: 'onBlur',
    }]" @change="cardCodeMsg" />
        </div>
        <div class="box">
          <van-field v-model="metaInfo.phoneNumber" name="phoneNumber" label="手机号码" placeholder="手机号码" :rules="[{
                pattern: /^1[3456789]\d{9}$/,
                message: '手机号码格式错误！',
                trigger: 'onBlur',
              },
    ]" @change="phoneNumberMsg" />
        </div>


        <gz-code-input @valueChange="valueChange" :requestData="requestData" requestMethod="post" requestUrl=""
          placeholder="验证码">
        </gz-code-input>
        <div>
          <van-button :loading="loading" block type="info" native-type="submit">下一步</van-button>
        </div>
      </van-form>
      <gz-authorization @input="input" :fileinfo="fileinfoRule" :identityinfo="identityinfoRule"
        v-model="typeValue"></gz-authorization>
    </div>
  </div>
</template>

<script>
  import {
    OCRUpload
  } from "@/components/customize";
  import Vue from 'vue';
  import {
    Form,
    Button,
    Field
  } from 'vant';


  Vue.use(Form);
  Vue.use(Field);
  Vue.use(Button)
  export default {
    name: 'authMate',
    components: {
      OCRUpload
    },
    data() {
      return {
        loading: false,
        jiek: false,
        typeValue: null,
        uuid: '',
        card: '',
        instId: '',
        smsResults: '',
        dateResults: '',
        requestData: {
          mateName: '',
          tel: '',
          instId: ''
        },
        metaInfo: {
          connId: '',
          authorizedName: '',
          cardName: '身份证',
          cardCode: '',
          phoneNumber: ''
        },
        fileinfoRule: [{
            name: "对外提供个人信息授权书",
            key: "network"
          },
          // { name: "人脸识别授权书", key: "faceRecognition" },
          {
            name: "个人征信客户授权书",
            key: "creditInvestigation"
          },
          {
            name: "个人信息及敏感信息授权书",
            key: "sensitive"
          },
          {
            name: "纳税人涉税信息查询授权书",
            key: "information"
          },
          // { name: "共同债务确认书", key: "jointDebt" },
        ],
        identityinfoRule: {
          personalFlag: false, //（是否个人授权书）
          xtlsh: '', //（系统流水号）
          cardName: '101', //（身份证类型名称）  000101
          cardCode: '', //（身份证号）
          authorizedName: '', //（客户姓名）

          tel: ''
        },
        isReadly: false,
      }
    },
    created() {
      this.requestData.instId = this.getParam('instId') || ''
      this.uuid = this.getParam('uuid') || ''
      this.instId = this.getParam('instId') || ''
      this.identityinfoRule.xtlsh = this.getParam('instId') || ''
      this.identityinfoRule.personalFlag = this.getParam('personalFlag') ?
        this.$route.query.personalFlag :
        false;
      if (!this.instId && instId) {
        this.instId = instId;
      }
      this.getint()
      //   this.baseService
      //                 .postForm(this.__ctx + "/cifPer/exp/queryMateInfo", {connId: this.instId})
      //                 .then((res) => {
      //                        if (res.data) {
      //                         this.metaInfo = res.data
      //                           this.metaInfo.cardName = '身份证'

      //                  this.requestData.mateName = res.data.authorizedName
      //                  this.requestData.tel = res.data.phoneNumber
      //                  this.requestData.instId = res.data.connId
      //                  this.identityinfoRule.cardName = '101'
      //                  this.identityinfoRule.cardCode = res.data.cardCode
      //                  this.identityinfoRule.authorizedName = res.data.authorizedName
      //                  this.identityinfoRule.tel = res.data.phoneNumber
      //                        }else{
      //                          this.metaInfo =  {
      //                                 connId:'',
      //                                 authorizedName:  '',
      //                                 cardName:  '身份证',
      //                                 cardCode: '',
      //                                 phoneNumber: ''
      //                              }
      //                           this.requestData.mateName = ''
      //                           this.requestData.tel = ''
      //                           this.requestData.instId = this.instId

      //                            this.identityinfoRule.cardName = '101'
      //                            this.identityinfoRule.cardCode = ''
      //                            this.identityinfoRule.authorizedName =''
      //                            this.identityinfoRule.tel =''
      //                        }

      //                 })

      // this.baseService
      //                 .postForm(this.__ctx + "/cifPer/exp/queryRes", {instId:this.requestData.instId,})
      //                 .then((res) => {
      //                  if (res.isOk) {
      //                   this.jiek = true
      //                   if (res.data) {
      //                     this.typeValue = 1
      //                      this.smsResults = res.data.smsResults
      //                   this.dateResults = res.data.dataResults
      //                   }else{
      //                     this.typeValue = 0
      //                      this.smsResults = ''
      //                       this.dateResults = ''
      //                   }

      //                  }
      //                 })
    },
    methods: {
      cardCodeMsg(e) {
        this.identityinfoRule.cardCode = e.target._value
      },
      getint() {
        // 获取token是http://localhost:8080/biz/loginBy/jwtForMobile（行内）参数是account默认wxApplets、audience默认Applets
        //微信银行 account/audience: wxBank, 手机银行 account/audience: mobileBank
        return new Promise((resolve) => {
          let defer = this.baseService.postForm(
            this.__ctx + "/biz/loginBy/jwtForMobile", {
              account: process.env.account, //默认
              audience: process.env.account, //默认
            }
          );
          defer.then((data) => {
            if (data.isOk) {
              resolve();
            } else {
              this.$vux.toast.show({
                type: "warn",
                text: data.msg,
              });
            }
          });
        });
      },
      authorizeNameMsg(e) {
        this.requestData.mateName = e.target._value
        this.identityinfoRule.authorizedName = e.target._value

      },
      phoneNumberMsg(e) {
        this.requestData.tel = e.target._value
        this.identityinfoRule.tel = e.target._value
      },
      valueChange(val) {

        if (val.length > 5) {
          this.baseService
            .post(this.__ctx + "/message/checkCode", {
              instId: this.requestData.instId,
              tel: this.requestData.tel,
              credential: val
            })
            .then((res) => {
              if (res.isOk) {
                this.smsResults = '1'
                this.$vux.toast.show({
                  text: '校验成功',
                })

              } else {
                this.smsResults = '0'
                this.abTools.toast("校验失败！", "warn");
              }
            }).catch((err) => {

              this.abTools.toast(err.message, "warn");

            })
        }

      },
      input(val) {

        if (val) {
          this.dateResults = '1'
        } else {
          this.dateResults = '0'
        }
      },
      getOcrInfo(e) {

        let cardInfo = e.data
        cardInfo.forEach(async (v, i) => {
          switch (v.itemid) {
            // 姓名
            case 'name':
              this.$set(this.metaInfo, "authorizedName", v.itemstring)
              this.$set(this.identityinfoRule, "authorizedName", v.itemstring)
              this.$set(this.requestData, "mateName", v.itemstring)
              break;
              // 身份证号
            case 'id':
              this.$set(this.metaInfo, "cardCode", v.itemstring)
              this.$set(this.identityinfoRule, "cardCode", v.itemstring)
              break;
            case 'address':
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "ID_REGISADDR", v.itemstring)
              this.$set(this.data.incomingBusinessObj.CIF_PSL_ADDR, "ADDR", v.itemstring)
              break;
              //  出生日期
            case 'birth':
              // let birthDate = v.itemstring.replace(/\//g, '-')
              let dateStr = ''
              let age = ''
              if (v.itemstring) {
                let birthDate = v.itemstring.split('/')
                if (Number(birthDate[1]) < 10) {
                  birthDate[1] = '0' + birthDate[1]
                }
                if (Number(birthDate[2] < 10)) {
                  birthDate[2] = '0' + birthDate[2]
                }
                dateStr = birthDate.join('-')
                this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "BRTH_DAT", dateStr)
                //就算年龄
                age = await this.getAge(birthDate);
              }
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "BRTH_DAT", dateStr)
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "AGE", age)
              break;
              //  民族
            case 'nation':
              let nation = ''
              if (v.itemstring) {
                nation = await this.getDictInfo(v.itemstring + '族')
              }
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "RACE_COD", nation)
              break;
              //  性别
            case 'sex':
              let gender = ''
              if (v.itemstring) {
                if (v.itemstring == '男') {
                  gender = '1'
                }
                if (v.itemstring == '女') {
                  gender = '2'
                }
              }
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "GENDER", gender)
              break;
              //  签发机构
            case 'authority':
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "ISSUCTF_AHR", v.itemstring)
              break;
              //  身份证生效日期+截至日期
            case 'valid_date':
              let start = ''
              let end = ''
              if (v.itemstring) {
                let date = v.itemstring.split('-')
                start = date[0].replace(/\./g, '-')
                end = date[1].replace(/\./g, '-')
              }
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "IDCARD_START_ISSUE_DATA", start)
              this.$set(this.data.incomingBusinessObj.CIF_PSL_BASE, "IDCARD_END_ISSUE_DATA", end)
              break;
          }
        })
      },
      getParam(name) {
        var locUrl = window.location.search.substr(1);
        var aryParams = locUrl.split("&");
        var rtn = "";
        for (var i = 0; i < aryParams.length; i++) {
          var pair = aryParams[i];
          var aryEnt = pair.split("=");
          var key = aryEnt[0];
          var val = aryEnt[1];
          if (key != name) continue;
          if (rtn == "") {
            rtn = val;
          } else {
            rtn += "," + val;
          }
        }
        return rtn;
      },
      onSubmit(values) {
        // this.smsResults = '1'
        // this.dateResults = '1'
        this.loading = true
        values.connId = this.instId
        //       this.baseService
        //               .post(this.__ctx + "/cifPer/exp/updateMateInfo", values)
        //               .then((res) => {
        //               })
        this.baseService
          .postForm(this.__ctx + "/cifPer/exp/saveDataSmsRes", {
            instId: this.requestData.instId,
            dataResults: this.dateResults,
            smsResults: this.smsResults
          })
          .then((res) => {

          })
        let that = this
        if (that.smsResults != '1') {
          that.abTools.toast("请进行短信验证！", "warn");
          that.loading = false
          return false
        }
        if (that.dateResults != '1') {
          that.abTools.toast("请阅读相关规则！", "warn");
          that.loading = false
          return false
        }
        if (values.cardName == '身份证') {
          values.cardName = '101'
        }
        localStorage.setItem('mateMsgObj', JSON.stringify(values))
        that.baseService
          .post(that.__ctx + "/cifPer/exp/addMateInfo", values)
          .then((res) => {
            that.loading = false
            if (res.isOk) {
              that.$vux.toast.show({
                text: res.msg,
              })
              that.$router.push({
                path: '/auth/verifyFace',
                query: {
                  instId: that.requestData.instId //参数
                }
              })
            } else {
              this.abTools.toast(res.msg, "warn");
            }
          })


      }
    },
  }
</script>

<style lang='less' scoped>
  .mateBox {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;

    flex-direction: column;
  }

  .van-button--block {
    position: fixed;
    bottom: 0;
    background-color: rgb(204, 52, 0);
    border: none;
  }

  .van-form {
    margin-top: 30px;

  }

  .authorization {
    margin-bottom: 50px;

  }

  .box {
    position: relative;

    /deep/ .input-box {
      left: auto;
      right: 10px;
      top: 8px;
    }
  }
</style>